package com.netstar.salesman_90dsp.activity;

import java.io.UnsupportedEncodingException;

import org.apache.http.Header;

import roboguice.inject.InjectView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.netstar.salesman_90dsp.BaseActivity;
import com.netstar.salesman_90dsp.R;
import com.netstar.salesman_90dsp.config.WebServerConfig;
import com.netstar.salesman_90dsp.engine.LoginEngine;
import com.netstar.salesman_90dsp.model.UserModel;

/**
 * 登录界面
 * 
 * @author zhangshuai
 * 
 */
public class LoginActivity extends BaseActivity {
	/**
	 * 用户帐号
	 */
	@InjectView(R.id.activity_login_et_user_account)
	TextView activity_login_et_user_account;
	/**
	 * 用户密码
	 */
	@InjectView(R.id.activity_login_et_user_pwd)
	TextView activity_login_et_user_pwd;
	/**
	 * 自动登录
	 */
	@InjectView(R.id.activity_login_cb_auto_login)
	CheckBox activity_login_cb_auto_login;
	/**
	 * 登录按钮
	 */
	@InjectView(R.id.activity_login_bt_login)
	Button activity_login_bt_login;
	/**
	 * 登录请求回调类
	 */
	private LoginHttpHandler loginHttpHandler;
	/**
	 * 登录业务逻辑类
	 */
	private LoginEngine loginEngine;

	@Override
	public void subInitContentView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_login);
	}

	@Override
	public void subInitView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void subInitParam() {
		// 网路请求回调类
		loginHttpHandler = new LoginHttpHandler();
		// 登录业务逻辑类
		loginEngine = new LoginEngine(activityContext);
		// 获取上次登录保留的帐号
		String userAccount = loginEngine.getUserAccount();
		// 如果帐号不为空，说明上次登陆过，将全部信息取出，看是否自动登录
		String userPWD;
		boolean isAutoLogin;
		if (!TextUtils.isEmpty(userAccount)) {
			userPWD = loginEngine.getUserPWD();
			isAutoLogin = loginEngine.isAutoLogin();
			// 设置view 的值
			activity_login_et_user_account.setText(userAccount);
			activity_login_et_user_pwd.setText(userPWD);
			activity_login_cb_auto_login.setChecked(isAutoLogin);
			// 判断是否自动登录
			if (isAutoLogin) {
				startLogin();
			}
		}

	}

	@Override
	public void subSetOnclick() {
		// 登录按钮
		setOnclickWithDefaultListener(activity_login_bt_login);
	}

	@Override
	public void subRunSomeThing() {
		// TODO Auto-generated method stub

	}

	@Override
	public synchronized void callbackWithDefaultListener(View view) {
		switch (view.getId()) {
		case R.id.activity_login_bt_login:
			// 登录按钮点击
			if (waittingAlertDialog == null) {
				startLogin();
			}
			break;

		default:
			break;
		}
		super.callbackWithDefaultListener(view);
	}

	/**
	 * 开始登录
	 */
	public void startLogin() {
		// 错误信息
		String errorMsg = null;
		// 开启等待框
		waittingAlertDialog = dialogTool.getWaittingDialog(-1, "登陆中，请稍候。。。");
		waittingAlertDialog.show();
		// 获取输入的值
		String userAccount = getStringFromView(activity_login_et_user_account);
		String userPWD = getStringFromView(activity_login_et_user_pwd);
		do {
			// 帐号不得为空
			if (TextUtils.isEmpty(userAccount)) {
				errorMsg = getResources()
						.getString(
								R.string.activity_tlogin_string_errormsg_useraccount_is_null);
				break;
			}
			// 密码不得为空
			if (TextUtils.isEmpty(userPWD)) {
				errorMsg = getResources()
						.getString(
								R.string.activity_tlogin_string_errormsg_userpwd_is_null);
				break;
			}
			// 请求网络
			try {
				asyncHttpClient.post(
						WebServerConfig.getUrl(WebServerConfig.loginAction),
						loginEngine.getRequestParams(userAccount, userPWD),
						loginHttpHandler);
			} catch (UnsupportedEncodingException e) {
				errorMsg = e != null ? e.getMessage() : getResources()
						.getString(R.string.common_string_unknown_mistake);
				e.printStackTrace();
			}
		} while (false);
		// 提示错误信息
		if (!TextUtils.isEmpty(errorMsg)) {
			endLogin(false, errorMsg, null);
		}
	}

	/**
	 * 结束登录
	 */
	public void endLogin(boolean isSuccess, String msg, UserModel userModel) {
		// 关闭等待框
		waittingAlertDialog.dismiss();
		waittingAlertDialog = null;

		if (isSuccess) {
			// 保存登录信息
			loginEngine.saveUserInfo(
					getStringFromView(activity_login_et_user_account),
					getStringFromView(activity_login_et_user_pwd),
					activity_login_cb_auto_login.isChecked());
			// 将用户信息存入配置类
			loginEngine.copyInfoToConfig(userModel);
			// 跳转入主界面
			Intent intent = new Intent();
			intent.setClass(activityContext, MainActivity.class);
			startActivity(intent);
			finish();
		} else {
			msg = TextUtils.isEmpty(msg) ? getResources().getString(
					R.string.common_string_unknown_mistake) : msg;
			Toast.makeText(activityContext, msg, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 登录请求回调类
	 * 
	 * @author zhangshuai
	 * 
	 */
	private class LoginHttpHandler extends
			BaseJsonHttpResponseHandler<UserModel> {
		private String errorMsg;

		public LoginHttpHandler() {
			super();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable arg2,
				String arg3, UserModel arg4) {
			errorMsg = null;
			errorMsg = getStringFromThrowable(arg2);
			endLogin(false, errorMsg, null);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String arg2,
				UserModel arg3) {
			errorMsg = null;
			// 成功，不仅是网络请求成功，也得是验证成功，才是成功
			if (arg3 != null && arg3.isResult()) {
				endLogin(true, null, arg3);
			} else {
				if (arg3 == null || arg3 == null) {
					errorMsg = null;
				} else {
					errorMsg = arg3.getMsg();
				}
				endLogin(false, errorMsg, null);
			}

		}

		@Override
		protected UserModel parseResponse(String arg0) throws Throwable {
			return new ObjectMapper().readValues(
					new JsonFactory().createParser(arg0.substring(1,
							arg0.length() - 1)), UserModel.class).next();

		}

	}
}
